/**
 * @typedef {Object} ScanResult 条码扫描结果类
 * @property {string} result 所扫码的内容
 * @property {string} scanType 所扫码的类型
 * @property {string} charSet 所扫码的字符集
 * @property {string} path 当所扫的码为当前小程序二维码时，会返回此字段，内容为二维码携带的 path
 * @property {string} rawData 原始数据，base64编码
 */

/**
 * 条码扫描器类
 */
export default class CodeScanner
{
    _data
    /**
     * 是否只能从相机扫码，不允许从相册选择图片
     * @param {boolean} onlyFromCamera 默认false
     */
    set onlyFromCamera(onlyFromCamera){
        this._data.onlyFromCamera = Boolean(onlyFromCamera)
    }
    /**
     * 是否只能从相机扫码，不允许从相册选择图片
     * @returns {boolean}
     */
    get onlyFromCamera(){
        return Boolean(this._data.onlyFromCamera)
    }
    /**
     * 扫码类型
     * @param {string|string[]} scanTypes barCode=一维码；qrCode=二维码；datamatrix=Data Matrix 码；pdf417=PDF417 条码；默认 ['barCode','qrCode']
     */
    set scanTypes(scanTypes){
        if(!Array.isArray(scanTypes)){
            scanTypes = [scanTypes]
        }
        this._data.scanTypes = scanTypes
    }
    /**
     * 扫码类型列表
     * @returns {string[]}
     */
    get scanTypes(){
        if(!Array.isArray(this._data.scanTypes) || this._data.scanTypes.length === 0){
            return ['barCode','qrCode']
        }
        return this._data.scanTypes
    }
    /**
     * 执行扫描
     * @returns {Promise<ScanResult>}
     */
    doScan(){
        return (new Promise((resolve, reject)=>{
            wx.scanCode({
                onlyFromCamera: this.onlyFromCamera,
                scanType: this.scanTypes,
                success: function(res){
                    resolve(res)
                },
                fail: function(err){
                    reject(err)
                }
            })
        }))
    }
}